<template>
    <div class="add-templates">
        <a-spin :spinning="loading">
            <div class="head">
                <span class="head-title">{{
                    formState.tempType == 'add'
                        ? t('yl.tmpAddTitle')
                        : formState.tempType == 'edit'
                        ? t('yl.tmpEditTitle')
                        : t('yl.tmpCopyTitle')
                }}</span>
                <div>
                    <a-button @click="goBack">返回</a-button>
                    <a-button type="primary" @click="nextStep">下一步</a-button>
                </div>
            </div>
            <div style="margin-top: 15px">
                <a-form class="dept-model" layout="horizontal" :model="formState" :rules="rules" ref="formRef">
                    <a-form-item class="full-width" :label="t('yl.tmpTitle')" name="name">
                        <a-input v-model:value="formState.name" :placeholder="t('yl.tmpTitle')" style="width: 200px" />
                    </a-form-item>
                    <a-form-item class="full-width" :label="t('yl.tmpSelectModel')" name="tagRatio">
                        <a-select
                            v-model:value="formState.tagRatio"
                            :placeholder="t('yl.tmpSelectModel')"
                            style="width: 200px"
                            @change="changSelectModel"
                            :disabled="formState.tempType !== 'add'"
                        >
                            <a-select-option :value="item.shortName" v-for="(item, index) in selectModels" :key="index">{{
                                item.shortName
                            }}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item class="full-width" :label="t('yl.tmpImgOptimize')" name="preProcAction">
                        <a-switch v-model:checked="formState.preProcAction" />
                    </a-form-item>

                    <a-form-item class="full-width" :label="t('yl.tmpDirection')" name="showWay">
                        <a-radio-group
                            v-model:value="formState.showWay"
                            size="large"
                            :disabled="formState.tempType !== 'add' || !formState.tagRatio"
                            @change="changShowWay"
                        >
                            <a-radio-button :value="0" class="none"
                                ><i
                                    class="icon priceTag-hengxiang-weixuanzhong"
                                    style="font-size: 32px"
                                    :class="formState.showWay == 0 ? 'wayActive' : ''"
                                ></i
                            ></a-radio-button>
                            <a-radio-button :value="1" class="none"
                                ><i
                                    class="icon priceTag-shuxiang-weixuanzhong"
                                    style="font-size: 43px"
                                    :class="formState.showWay == 1 ? 'wayActive' : ''"
                                ></i
                            ></a-radio-button>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item class="full-width" :label="t('yl.tmpSplitStyle')" name="splitStyle">
                        <a-radio-group v-model:value="formState.splitStyle" size="large">
                            <a-radio-button
                                :value="item.styleCode"
                                class="none"
                                v-for="(item, index) in templateList"
                                :key="index"
                                :disabled="formState.tempType !== 'add'"
                                :class="formState.splitStyle == item.styleCode ? 'wayActive' : ''"
                            >
                                <i
                                    class="icon tmp-icon"
                                    :class="item.picTag"
                                    :style="formState.showWay == 0 ? 'font-size: 35px' : 'font-size: 48px'"
                                ></i
                            ></a-radio-button>
                        </a-radio-group>
                    </a-form-item>

                    <!-- <a-form-item class="full-width" :label="t('yl.previewEffect')" name="name">
                    <a-upload
                        v-model:file-list="fileList"
                        name="avatar"
                        list-type="picture-card"
                        class="avatar-uploader"
                        :show-upload-list="false"
                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                        :before-upload="beforeUpload"
                        @change="handleChange"
                    >
                        <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
                        <div v-else>
                            <loading-outlined v-if="loading"></loading-outlined>
                            <plus-outlined v-else></plus-outlined>
                            <div class="ant-upload-text">Upload</div>
                        </div>
                    </a-upload>
                </a-form-item> -->
                </a-form>
            </div>
        </a-spin>
    </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { PaginationQuery } from '@/types/table';
import { FundOutlined, CopyOutlined, EyeOutlined, AppstoreOutlined, UnorderedListOutlined } from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import { addModel, editModel } from '@/api/warehouse';
import { TableState, CheckAble } from '@/types/table';
import { getTempQueryStyle, AddTemplate, getTemplate } from '@/api/templates';
// 表单校验规则
const initRules = (t: fn) => {
    return {
        name: [{ required: true, message: t('yl.tmpTitle'), trigger: 'blur' }],
        tagRatio: [{ required: true, message: t('yl.tmpSelectModel'), trigger: 'blur' }],
        showWay: [{ required: true, message: t('yl.tmpDirection'), type: 'number', trigger: 'blur' }],
        splitStyle: [{ required: true, message: t('yl.tmpSplitStyle'), type: 'number', trigger: 'blur' }],
    };
};

interface DeptState {
    name: string;
    showWay: string | number;
    splitStyle: string | number;
    preProcAction: string | number;
    templateImgeUrl: string;
    tagRatio: string | number;
    tagColour: string;
    tagRatioName: string;
    templateCommons: any[];
    infoHeight: string | number;
    infoWidth: string | number;
    type: string | number;
    industryId: string | number;
    temLang: string | number;
    tempType: string;
}
import useTables from './listTable';
export default defineComponent({
    name: 'department',
    components: {
        CopyOutlined,
        FundOutlined,
        EyeOutlined,
        AppstoreOutlined,
        UnorderedListOutlined,
    },
    props: {
        templateCode: {
            type: String,
            default: '',
        },
        tempType: {
            type: String,
            default: 'add',
        },
    },
    setup(props, { emit }) {
        const { t } = useI18n();
        const formState: DeptState = reactive({
            name: '', // 模板名称
            type: 1,
            industryId: 41,
            // 显示方向 0:横 1:竖
            showWay: 0,
            // 分屏样式
            splitStyle: '',
            // 	图片预处理(0:无预处理,1:抖动处理)
            preProcAction: 0,
            // 模板预览图
            templateImgeUrl: '',
            // 支持分辨率ID
            tagRatio: '',
            // 颜色ID
            tagColour: '',
            // 中文
            temLang: 1,
            tagRatioName: '',
            // 模板分屏
            templateCommons: [],
            // 父级大小
            infoHeight: 0,
            infoWidth: 0,
            tempType: props.tempType,
        });
        const templateList: any = ref([]);
        const loading = ref(false);
        // 角色信息
        let { getModelData, selectModels } = useTables;

        onMounted(async () => {
            loading.value = true;
            await getModelData();

            if (formState.tempType !== 'add') {
                loading.value = true;
                changTemplate();
            } else {
                const timer = setTimeout(() => {
                    loading.value = false;
                    clearTimeout(timer);
                }, 1000);
            }
        });
        // 查询模板信息
        const changTemplate = async () => {
            let data = await getTemplate(props.templateCode);
            formState.name = formState.tempType == 'copy' ? '' : data.content.templateName;
            formState.type = data.content.templateType;
            formState.industryId = data.content.templateIndustry;
            // 显示方向 0:横 1:竖
            formState.showWay = data.content.showWay;
            // 分屏样式
            formState.splitStyle = data.content.splitStyle;
            // 	图片预处理(0:无预处理,1:抖动处理)
            formState.preProcAction = data.content.preProcAction;
            // 模板预览图
            formState.templateImgeUrl = data.content.templateImgeUrl;
            // 支持分辨率ID

            // 颜色ID
            formState.tagColour = data.content.tagColour;
            // 中文
            formState.temLang = data.content.supportLanguage;
            // 模板分屏
            formState.templateCommons = data.content.templateCommons;

            for (let i = 0; i < selectModels.value.length; i++) {
                if (
                    selectModels.value[i].tagColour == data.content.tagColour &&
                    selectModels.value[i].tagRatio == data.content.tagRatio
                ) {
                    console.log(selectModels.value[i]);
                    formState.tagRatio = selectModels.value[i].shortName;

                    changSelectModel(formState.tagRatio);
                    break;
                }
            }
        };
        // 监听型号事件
        const changSelectModel = (val: string | number) => {
            console.log(val);
            selectModels.value.forEach((i: any) => {
                if (i.shortName == val) {
                    console.log(i);
                    // 根据型号查询Icon
                    changIconData(i.tagMeasureName);
                    formState.tagRatioName = i.tagRatioName;
                    formState.tagColour = i.tagColour;
                }
            });
        };

        // 根据型号查询Icon
        const changIconData = async (tagMeasureName: any) => {
            templateList.value = await getTempQueryStyle(formState.showWay, parseFloat(tagMeasureName));

            const timer = setTimeout(() => {
                loading.value = false;
                clearTimeout(timer);
            }, 500);
        };

        const changShowWay = (val: string | number) => {
            changSelectModel(formState.tagRatio);
        };
        // 表单校验
        const rules = initRules(t);
        const formRef = ref();
        const nextStep = () => {
            formRef.value.validate().then(() => {
                const info = formState.tagRatioName.split('*');
                const infoHeight = Number(info[1].substring(0, info[1].length - 2));
                formState.infoWidth = formState.showWay == 0 ? Number(info[0]) : infoHeight;
                formState.infoHeight = formState.showWay == 0 ? infoHeight : Number(info[0]);
                if (formState.tempType == 'add') {
                    formState.templateCommons = splitWHArrt(formState.infoWidth, formState.infoHeight);
                }

                let data = JSON.parse(JSON.stringify(formState));
                for (let i = 0; i < selectModels.value.length; i++) {
                    if (selectModels.value[i].shortName == formState.tagRatio) {
                        data.tagRatio = selectModels.value[i].tagRatio;
                        break;
                    }
                }
                console.log(data);
                emit('nextStep', data);
            });
        };
        //分屏数组
        const splitWHArrt = (width: number, height: number) => {
            let smallBox: any[] = [];
            let iconNum = 0;

            // 根据图标的下标样式切割不同的分屏
            for (let i = 0; i < templateList.value.length; i++) {
                if (templateList.value[i].styleCode == formState.splitStyle) {
                    iconNum = Number(templateList.value[i].picTag.replace(/[^0-9]/gi, ''));
                    break;
                }
            }
            console.log(iconNum);

            switch (iconNum) {
                case 1:
                    smallBox = smallBoxFun(width, height, 1, 'alignWith');
                    break;
                case 2:
                    smallBox = smallBoxFun(width, height, 2, 'alignWith');
                    break;
                case 3:
                    smallBox = smallBoxFun(width, height, 2, 'align');
                    break;
                case 4:
                    smallBox = smallBoxFun(width, height, 3, 'top');
                    break;
                case 5:
                    smallBox = smallBoxFun(width, height, 3, 'bottom');
                    break;
                case 6:
                    smallBox = smallBoxFun(width, height, 3, 'left');
                    break;
                case 7:
                    smallBox = smallBoxFun(width, height, 3, 'right');
                    break;
                case 8:
                    smallBox = smallBoxFun(width, height, 4, 'align');
                    break;
                case 9:
                    smallBox = smallBoxFun(width, height, 6, 'align');
                    break;
                case 10:
                    smallBox = smallBoxFun(width, height, 8, 'align');
                    break;
                default:
                    smallBox = smallBoxFun(width, height, 10, 'align');
                    break;
            }
            console.log(smallBox);
            smallBox.forEach((i) => {
                i.note = JSON.stringify(i.note);
            });
            return smallBox;
        };
        // 根据宽高计算不同的分屏样式
        const smallBoxFun = (width: number, height: number, num: number, align: string) => {
            let style = {
                position: 'relative',
                background: 'initial',
                color: '#000000',
                zIndex: 1,
                display: 'table-cell',
                fontSize: '14px',
                overflow: 'hidden',
                lineHeight: '100%',
                cursor: 'default',
                border: 'none',
                letterSpacing: '0px',
                fontFamily: 'Microsoft YaHei',
            };
            // 父亲width宽 height高   num生成个数   当三个时方向
            // alignWith判断上下样式 align左右规则   left，top,bottom,right 切割为3时定位
            let list: any = [];
            // 上下
            if (num == 1 || (num == 2 && align == 'alignWith')) {
                for (let i = 0; i < num; i++) {
                    list.push({
                        number: i,
                        content: '',
                        templateCommonId: '',
                        note: {
                            label: '背景图层',
                            tempGroup: [],
                            style: style,
                            left: 0,
                            top: (num == 1 && !i) || (num == 2 && !i && !i) ? 0 : height / 2,
                            height: num == 1 && !i ? height : height / 2,
                            width: width,
                        },
                    });
                }
                return list;
            }
            // 左右规则
            if (num !== 3 && align == 'align') {
                for (let i = 0; i < num; i++) {
                    list.push({
                        number: i,
                        content: '',
                        templateCommonId: '',
                        note: {
                            label: '背景图层',
                            tempGroup: [],
                            style: style,
                            left: i % 2 == 0 ? 0 : width / 2,
                            top: i % 2 == 0 ? (i * height) / (num / 2) / 2 : list[i - 1].note.top,
                            height: height / (num / 2) / 1,
                            width: width / 2,
                        },
                    });
                }
                return list;
            }
            // 3个不规则
            if (num == 3) {
                switch (align) {
                    case 'left':
                        for (let i = 0; i < num; i++) {
                            list.push({
                                number: i,
                                content: '',
                                templateCommonId: '',
                                note: {
                                    label: '背景图层',
                                    tempGroup: [],
                                    style: style,
                                    left: !i ? 0 : width / 2,
                                    top: !i || i == 1 ? 0 : height / 2,
                                    height: !i ? height : height / 2,
                                    width: width / 2,
                                },
                            });
                        }
                        break;
                    case 'top':
                        for (let i = 0; i < num; i++) {
                            list.push({
                                number: i,
                                templateCommonId: '',
                                content: '',
                                note: {
                                    label: '背景图层',
                                    tempGroup: [],
                                    style: style,
                                    left: !i || i == 1 ? 0 : width / 2,
                                    top: !i ? 0 : height / 2,
                                    height: height / 2,
                                    width: !i ? width : width / 2,
                                },
                            });
                        }
                        break;
                    case 'bottom':
                        for (let i = 0; i < num; i++) {
                            console.log(i);
                            list.push({
                                number: i,
                                templateCommonId: '',
                                content: '',
                                note: {
                                    label: '背景图层',
                                    tempGroup: [],
                                    style: style,
                                    left: num - 1 == i || i == 0 ? 0 : width / 2,
                                    top: num - 1 == i ? height / 2 : 0,
                                    height: height / 2,
                                    width: num - 1 == i ? width : width / 2,
                                },
                            });
                        }
                        break;
                    default:
                        for (let i = 0; i < num; i++) {
                            list.push({
                                number: i,
                                templateCommonId: '',
                                content: '',
                                note: {
                                    label: '背景图层',
                                    tempGroup: [],
                                    style: style,
                                    left: i == 2 ? width / 2 : 0,
                                    top: i == 2 || i == 0 ? 0 : height / 2,
                                    height: i == 2 ? height : height / 2,
                                    width: width / 2,
                                },
                            });
                        }
                        break;
                }
                return list;
            }
        };

        const goBack = () => {
            emit('goBack');

            // location.reload();
        };
        return {
            t,
            selectModels,
            templateList,
            formState,
            smallBoxFun,
            changSelectModel,
            changShowWay,
            nextStep,
            goBack,
            changTemplate,
            rules,
            formRef,
            loading,
        };
    },
});
</script>

<style lang="scss" scoped>
.head {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #ebebeb;
    padding-bottom: 10px;
    .head-title {
        font-size: 16px;
        font-weight: bold;
        color: #101010;
    }
    .ant-btn {
        margin-left: 5px;
    }
}
</style>
<style>
.ant-image-img,
.ant-image {
    width: 100%;
    height: 153px;
}
.none {
    line-height: 0 !important;
    font-size: 0 !important;
    height: 0 !important;
    white-space: nowrap;
    outline: 0 !important;
    border: none !important;
}
.wayActive {
    color: #1890ff !important;
}
</style>
